<?php

namespace app\services\product\product;

use app\dao\product\product\StoreProductTemplateDao;
use app\model\product\product\StoreProductTemplate;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;

class StoreProductTemplateServices extends BaseServices
{
    public function __construct(StoreProductTemplateDao $dao)
    {
        $this->dao = $dao;
    }

    public function getList(array $where)
    {
        [$page, $limit] = $this->getPageValue();
        $list = $this->dao->getList($where, $page, $limit);

        return [
            'list'  =>  $list->items(),
            'count'  =>  $list->count(),
        ];
    }

    public function all()
    {
        return StoreProductTemplate::field('id,template_name,merchant_params')->select()->toArray();
    }

    public function save(int $id, array $data)
    {
        if (!isset($data['template_name']) || $data['template_name'] == '') throw new AdminException(30007);
        if (empty($data['merchant_params'])) throw new AdminException(30008);

        if ($id) {
            $data['upd_time'] = time();
            $res = $this->dao->update($id, $data);
            if (!$res) throw new AdminException(10022);
        } else {
            $data['add_time'] = time();
            $data['upd_time'] = 0;
            $res = $this->dao->save($data);
            if (!$res) throw new AdminException(10022);
        }

    }


    /**
     * 删除
     * @param int $id
     */
    public function del(int $id, int $index)
    {
        if ($index == -1) throw new AdminException(30009);

        $template = $this->dao->get($id);
        $merchant_params_array = (array)$template->merchant_params;
        unset($merchant_params_array[$index]);
        $data = [
            'upd_time'  =>  time(),
            'merchant_params'   =>  array_values($merchant_params_array),
        ];

        $res = $this->dao->update($id, $data);
        if (!$res) throw new AdminException(100008);
    }
}